<!--  -->
<script setup>
import RankSwitcher from '@/components/RankSwitcher.vue'
import IconLabel from '@/components/IconLabel.vue'
import SubmitBtn from '@/components/button/SubmitBtn.vue'
import CommentBox from '@/components/commentBox/CommentBox.vue'
import UsrProfile from '@/components/UsrProfile.vue'
import Card from '@/components/Card.vue'
import Tip from '@/components/tip'
import ReportWindow from './components/ReportWindow.vue'
import useQuestInfo from './composable/useQuestInfo'
import useAnswerInfo from './composable/useAnswerInfo'
import LikeOrBad from './components/LikeOrBad.vue'
import Toc from './components/Toc.vue'
import {
  addAnswerAPI,
  deleteAnswerAPI,
  updateAnswerAPI,
  acceptAnswerAPI,
  cancelAcceptAnswerAPI
} from '@/apis/answer'
import { deleteQuestionAPI } from '@/apis/quest'
import { reportAPI } from '@/apis/report'
import { ref, nextTick, watch } from 'vue'
import { useBreadsStore } from '@/stores'
import { useRoute, useRouter } from 'vue-router'
import { format } from '@/utils/time'
import { render } from '@/utils/markdown'
import { us } from '@/utils/userState'
import PopWindow from '@/components/PopWindow.vue'
import PopConfirm from '@/components/PopConfirm.vue'

const route = useRoute()
const router = useRouter()
const initOrder = route.query.order || 'newest'

const { setBreadCrumbs } = useBreadsStore()
setBreadCrumbs([{ title: '问题列表', path: '/questions' }, { title: '问题详情' }])

const { questInfo } = useQuestInfo()
const { answerInfo, refreshAnswerData } = useAnswerInfo()

const tocLinks = ref([])
const articleRef = ref(null)
const answerContent = ref('')
const reportWinVisible = ref(false)
const addAnswerWinVisible = ref(false)
const reportInfo = ref(null)
const reportForm = ref(null)
const deleteWinVisible = ref(false)
const deleteAnsWinVisible = ref(false)
const deleteAnswerInfo = ref(null)

watch(questInfo, () => {
  nextTick(generateToc)
})

function doAnswer(content) {
  addAnswerAPI({ questionId: questInfo.value.id, content })
    .then(() => {
      answerContent.value = ''
      Tip.success('回答成功')
      refreshAnswerData(initOrder)
    })
    .catch(() => Tip.error('回答失败'))
}

function setDeleteAnswer(answer) {
  deleteAnswerInfo.value = answer
  deleteAnsWinVisible.value = true
}

function doDeleteAnswer() {
  deleteAnswerAPI(deleteAnswerInfo.value.id)
    .then(() => {
      Tip.success('删除成功')
      refreshAnswerData(initOrder)
    })
    .catch(() => Tip.error('删除失败'))
    .finally(() => deleteAnsWinVisible.value = true)
}

function doDeleteQuest() {
  deleteQuestionAPI(questInfo.value.id)
    .then(() => {
      Tip.success('删除成功')
      router.push('/questions')
    }).catch(() => Tip.error('删除失败'))
    .finally(() => deleteWinVisible.value = false)
}


function doReportCheck(userInfo, type, obj) {
  if (us.value.loggedUseId == userInfo.id) {
    Tip.error('不能举报自己')
    return
  }
  if (type == 0) {
    reportInfo.value = `文章标题：${questInfo.value.title}，文章作者：${userInfo.username}`
    reportForm.value = {
      objectId: questInfo.value.id,
      reportedUserId: userInfo.id,
      content: questInfo.value.content,
      objectType: type
    }
  } else if (type == 1) {
    reportInfo.value = `用户 ${userInfo.username} 的回答`
    reportForm.value = {
      objectId: obj.id,
      reportedUserId: userInfo.id,
      content: obj.content,
      objectType: type
    }
  }
  reportWinVisible.value = true
}

function doReport(form) {
  reportForm.value.userId = us.value.loggedUseId
  reportForm.value.flaggedContent = form.reason.join(',')
  reportForm.value.extraInfo = form.info
  reportAPI(reportForm.value).then(() => {
    reportWinVisible.value = false
    Tip.success('举报成功')
  }).catch(() => {
    Tip.error('举报失败')
  })
}

function doAccept(answer) {
  acceptAnswerAPI(answer.id).then(() => {
    Tip.success('采纳成功')
    answer.adopted = 1
  }).catch(() => {
    Tip.error('采纳失败')
  })
}

function doCancelAccept(answer) {
  cancelAcceptAnswerAPI(answer.id).then(() => {
    Tip.success('取消采纳成功')
    answer.adopted = 0
  }).catch(() => {
    Tip.error('取消采纳失败')
  })
}

function generateToc() {
  tocLinks.value.length = 0
  let nodes = articleRef.value.querySelectorAll('h1,h2,h3,h4,h5')
  for (let i = 0; i < nodes.length; i++) {
    let node = nodes[i]
    let reg = /^H[1-6]{1}$/
    if (reg.test(node.tagName) && !node.id)
      node.id = `h-${parseInt(node.tagName.substring(1))}-${i}`
    let toc = {
      id: node.id,
      title: node.innerText,
    }
    tocLinks.value.push(toc)
  }
}

const orderType = [
  { title: '最新', order: 'newest' },
  { title: '最热', order: 'hot' },
]
</script>

<template>
  <div v-if="questInfo" class="view-container">
    <PopConfirm :condition="deleteWinVisible" @submit="doDeleteQuest" @close="deleteWinVisible = false" topic="Delete?">
      <p>将删除提问“ {{ questInfo.title }} ”，是否继续？</p>
      <p v-if="answerInfo.length != 0">此问题拥有回答，不建议删除</p>
    </PopConfirm>
    <PopConfirm :condition="deleteAnsWinVisible" @submit="doDeleteAnswer" @close="deleteAnsWinVisible = false"
      topic="Delete?">
      <p>将删除用户“ {{ deleteAnswerInfo?.userInfo.displayName }} ” 的回答，是否继续？</p>
      <p v-if="deleteAnswerInfo?.adopted == 1">此回答已采纳，不建议删除</p>
    </PopConfirm>
    <ReportWindow :condition="reportWinVisible" @submit="doReport" :info="reportInfo" @close="reportWinVisible = false">
    </ReportWindow>
    <PopWindow :condition="addAnswerWinVisible" @close="addAnswerWinVisible = false">
      <div class="comment-box" v-if="us.isLogged">
        <CommentBox v-model="answerContent" @onSubmit="doAnswer" style="margin-top: 4em" />
      </div>
    </PopWindow>
    <div class="left-wrapper">
      <div class="header">
        <div v-if="questInfo.pin" class="icon icon-pin"></div>
        <h1 class="title">
          {{ questInfo.title }}
          <span v-if="questInfo.status !== 'ACTIVE'" style="color:grey">{{ questInfo.status }} </span>
        </h1>
      </div>
      <div class="info">
        <span class="info-item">发布于 {{ format(questInfo.createAt, 'YYYY-MM-DD') }}</span>
        <span v-if="questInfo.updateAt">编辑于{{ format(questInfo.updateAt, 'YYYY-MM-DD') }}</span>
        <span class="info-item">阅读次数 {{ questInfo.viewCount }}</span>
        <span class="info-item"></span>
      </div>
      <div class="tags">
        <RouterLink v-for="(tag, i) in questInfo.tags" :key="i" :to="`/tag/${tag.slugName}`" class="tag">
          {{ tag.displayName }}
        </RouterLink>
      </div>
      <div ref="articleRef" class="body" v-html="render(questInfo.content)"></div>
      <div class="footer">
        <div class="ops">
          <LikeOrBad :init-cnt="questInfo.voteCount" :init-status="questInfo.voteStatus"
            :user-id="questInfo.userInfo.id" :object-id="questInfo.id" object-type="0" />
          <div v-if="us.isLogged" class="report op-item" @click="doReportCheck(questInfo.userInfo, 0, questInfo)">举报
          </div>
          <div v-if="us.isStaff" class="ops">
            <RouterLink :to="`/question/${questInfo.id}/edit`">
              <div class="op-item">编辑</div>
            </RouterLink>
            <div class="op-item" @click="deleteWinVisible = true">删除</div>
            <div class="op-item">操作</div>
          </div>
        </div>
        <div class="authors">
          <UsrProfile :info="'声望' + questInfo.userInfo.ranks" :data="questInfo.userInfo" />
        </div>
        <div class="fast-comment">
          <div @click="addAnswerWinVisible = true">Add Answer</div>
          <div>+</div>
        </div>
      </div>
      <div class="comment-container">
        <div class="header" id="article-footer">
          <div>共 {{ answerInfo.length }} 回答</div>
          <RankSwitcher :order-type="orderType" :init-type="initOrder" @on-switch-order="refreshAnswerData" />
        </div>
        <div class="comment" v-for="answer in answerInfo" :key="answer.id">
          <div class="comment-left">
            <div class="flex">
              <div v-if="answer.adopted" class="accepted-sign">
                <IconLabel icon-name="answer">已采纳</IconLabel>
              </div>
              <div v-if="us.isStaff">
                <SubmitBtn v-if="!answer.adopted" class="accept" @click="doAccept(answer)">采纳</SubmitBtn>
                <SubmitBtn v-else class="accept" @click="doCancelAccept(answer)">取消采纳</SubmitBtn>
              </div>
            </div>
            <div class="content">{{ answer.content }}</div>
            <div class="footer">
              <LikeOrBad :init-cnt="answer.voteCount" :init-status="answer.voteStatus" :user-id="answer.userInfo.id"
                :object-id="answer.id" object-type="2"></LikeOrBad>
              <div class=" fast-comment">
                <!-- <div>comment</div> -->
                <div>+</div>
              </div>
            </div>
          </div>
          <div class="comment-right">
            <div class="ops">
              <div v-if="us.isLogged" class="report op-item" @click="doReportCheck(answer.userInfo, 2, answer)">举报</div>
              <div v-if="us.isStaff" class="ops">
                <RouterLink :to="`/answer/${questInfo.id}/edit`">
                  <div class="op-item">编辑</div>
                </RouterLink>
                <div class="op-item" @click="setDeleteAnswer(answer)">删除</div>
              </div>
            </div>
            <div class="comment-author-info">
              <UsrProfile :data="questInfo.userInfo" :info="'回答于' + format(answer.createAt, 'YYYY-MM-DD')" />
            </div>
          </div>
        </div>

      </div>
      <div class="load">
        <SubmitBtn class="load-more" @click="loadMoreAnswer">load more</SubmitBtn>
      </div>
    </div>
    <div class="right-wrapper">
      <Card topic="最佳答案">
        {{ answerInfo[0]?.adopted ? answerInfo[0]?.content : '无' }}
      </Card>
      <!-- <Card topic="大纲"> -->
      <Toc :toc-links="tocLinks"></Toc>
      <!-- </Card> -->
    </div>
  </div>
</template>

<style scoped lang="scss">
.view-container {
  display: flex;
  justify-content: space-between;
  min-height: 100%;
}

.comment-box {
  margin-top: auto;
}

.left-wrapper {
  flex: 1;
  padding-right: 1em;
  border-right: 1px dashed var(--border-secondary);


  .header {
    display: flex;
    gap: 1em;
    align-items: center;
  }

  .info {
    display: flex;
    gap: 1em;
    margin: 1em 0;
    color: var(--text-secondary);
  }

  .tags {
    display: flex;
    align-items: center;
    margin: 1em 0 2em;
    font-size: 0.8em;
    color: var(--text-secondary);

    .tag {
      margin-right: 0.5em;
      padding: 0.2em 0.5em;
      border-radius: 2px;
      background-color: var(--bgc-secondary);

      &:hover {
        background-color: var(--bgc-primary);
      }
    }
  }

  .body {
    border-top: 1px dashed var(--border-secondary);
    border-bottom: 1px dashed var(--border-secondary);


    &::after {
      content: "The End";
      font-family: "Bookman Old Style", serif;
      margin: 3em auto 1em;
      text-align: center;
      display: block;
      font-size: 1.5em;
      color: var(--text-01);
    }
  }

  .ops {
    display: flex;
    align-items: center;
    gap: 1em;
    color: grey;

    .op-item {
      cursor: pointer;

      &:hover {
        color: var(--text-01);

      }
    }
  }

  .footer {
    margin-top: 1em;



    .authors {
      margin: 1em 0;
      display: flex;
      justify-content: flex-end;
    }

    .fast-comment {
      margin: 1em 0;
      display: flex;
      justify-content: flex-start;
      gap: 1em;

      div {
        padding: 0.5em 1em;
        border-radius: 5px;
        background-color: var(--bgc-secondary);
        color: var(--text-secondary);
        cursor: pointer;

        &:hover {
          background-color: var(--bgc-primary);
        }
      }
    }
  }

  .comment-container {
    margin-top: 1em;

    .header {
      display: flex;
      justify-content: space-between;
      padding-bottom: 2em;
      border-bottom: 3px solid var(--border-secondary);
    }

    .comment {
      padding: 1em 0;
      border-bottom: 1px solid var(--border-secondary);
      display: flex;

      &:hover {

        .comment-right .ops {
          visibility: visible;
          opacity: 1;
        }
      }

      .comment-left {
        flex: 1;
      }

      .comment-right {
        display: flex;
        flex-direction: column;

        .ops {
          margin-left: auto;
          visibility: hidden;
          opacity: 0;
          transition: all 0.3s ease-in-out;
        }

        .comment-author-info {
          margin-top: auto;
        }
      }


      .accepted-sign {
        border-left: 2px solid green;
        padding-left: 1em;
      }

      .content {
        margin: 15px 0 10px;
      }

      .footer {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 1em;

        .fast-comment {
          flex: 1;
        }
      }
    }
  }


}

.right-wrapper {
  position: sticky;
  overflow-y: auto;
  top: 50px;
  z-index: 90;
  height: 100%;

  width: 300px;
  padding: 0 1em;

  .card {
    border: 1px solid var(--border-secondary);
    border-bottom: 0;
    border-radius: 2px;
    margin-bottom: 1em;

    .card-topic {
      padding: 1em;
      background-color: #d9e7d9;
      border-bottom: 1px solid var(--border-secondary);
    }

    .card-item {
      padding: 1em;
      border-bottom: 1px solid var(--border-secondary);
    }
  }
}

.load {
  display: flex;

  .load-more {
    margin: 2em auto 0;
  }
}

.icon-pin {
  mask-image: url('/static/svg/pin.svg');
}
</style>
